﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace OvertimeCalc
{
    public partial class frmMain : Form
    {
        private BindingList<Overtime> _source;

        public frmMain()
        {
            InitializeComponent();
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            var item = new Overtime()
                {
                    StartTime = startTime.Value,
                    EndTime = endTime.Value
                };
            item.NotifyEvent += new EventHandler(item_NotifyEvent);
            _source.Add(item);
            startTime.Value = Convert.ToDateTime("17:30");
            endTime.Value = Convert.ToDateTime("19:00");
        }

        void item_NotifyEvent(object sender, EventArgs e)
        {
            dataGridView.Invalidate();
            Calc();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            _source = new BindingList<Overtime>();
            _source.ListChanged += new ListChangedEventHandler(_source_ListChanged);
            dataGridView.DataSource = _source;
        }

        void _source_ListChanged(object sender, ListChangedEventArgs e)
        {
            if (e.ListChangedType == ListChangedType.ItemAdded)
            {
                (sender as BindingList<Overtime>)[e.NewIndex].Id = e.NewIndex + 1;
            }
            Calc();
        }

        private void Calc()
        {
            double sum = 0;
            foreach (var item in _source)
            {
                sum += item.SumTime;
            }
            lblSum.Text = string.Format("共:{0}分,{1}小时", sum, (sum / 60).ToString("0.00"));
        }

        private void delButton_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                _source.RemoveAt(dataGridView.SelectedRows[0].Index);
                Calc();
            }
        }
    }
}
